package javacource.redis.lock;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * Create by chenhd on 2021/10/23.
 */
@Component("redisLock")
public class RedisTemplateLock implements RedisLock {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public boolean lock(String key, String value, long second) {
        try {
            return redisTemplate.opsForValue().setIfAbsent(key, value, second, TimeUnit.SECONDS);
        } catch (Exception e) {
            //log
        }
        return false;
    }

    @Override
    public boolean unLock(String key, String value) {
        try {
            String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
            DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
            redisScript.setScriptText(script);
            long result = redisTemplate.execute(redisScript, Collections.singletonList(key), value);
            if (1L == result) {
                return true;
            }
        } catch (Exception e) {
            //log
        }
        return false;
    }
}
